import { login, logout, getUserInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: null,
  roles: []
}
const getters = {}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(res => {
          const { userInfo } = res
          commit('SET_TOKEN', userInfo.token)
          commit('SET_USERINFO', userInfo)
          setToken(userInfo.token)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USERINFO', '')
          removeToken()
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(res => {
          const { userInfo } = res
          commit('SET_USERINFO', userInfo)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced: true
}
